﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Sprout.Schedule.Web.Models;
using Sprout.Schedule.Web.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sprout.Schedule.Web.Attributes
{
    /// <summary>
    /// 返回值拦接器
    /// </summary>
    public class WebApiResultMiddleware : ActionFilterAttribute
    {
        /// <summary>
        /// 返回值前时处理
        /// </summary>
        /// <param name="context">返回上下文</param>
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            //模型验证处理逻辑
            if (!context.ModelState.IsValid)
            {
                context.Result = new ObjectResult(ModelStateHelper.GetModelStateResult(context.ModelState));
                //验证失败跳出
                return;
            }

            if (context.Result is ObjectResult)
            {
                var objectResult = context.Result as ObjectResult;
                if (objectResult.Value == null)
                {
                    context.Result = new ObjectResult(new ResponseResult());
                }
                else
                {
                    //如果返回值不是 ResponseResult 则进行处理
                    if ((objectResult.Value is ResponseResult) == false)
                    {
                        context.Result = new ObjectResult(new ResponseResult() { Data = objectResult.Value });
                    }
                }
            }
            else if (context.Result is EmptyResult)
            {
                context.Result = new ObjectResult(new ResponseResult());
            }
            else if (context.Result is ContentResult)
            {
            }
            else if (context.Result is StatusCodeResult)
            {
            }
        }
    }
}
